package com.xiaodu.jdbc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaodu.jdbc.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @author: dutianjie
 * @date: 2021/4/9
 * @version: v1.0.0
 * @description: 描述
 **/
@RestController
@RequestMapping("user")
@Api(tags = {"user操作"})
public class UserController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @ApiOperation(value = "添加用户信息", httpMethod = "POST", produces = MediaType.MULTIPART_FORM_DATA_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping({"", "add"})
    public String addUser(UserEntity userEntity) throws Exception {
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        Object[] params = new Object[]{id,
                userEntity.getuName(),
                userEntity.getPassword(),
                userEntity.getMoney(),
                new Date()};
        jdbcTemplate.update("insert into t_user(u_id,u_name,password,money,create_time) values(?,?,?,?,?)", params);
        return id;
    }

    @GetMapping({"{id}"})
    public UserEntity getUser(@PathVariable String id) throws Exception {
        return jdbcTemplate.queryForObject("select * from t_user where u_id = ?", new Object[]{id}, new BeanPropertyRowMapper<>(UserEntity.class));
    }

    @GetMapping({"v2/{id}"})
    public UserEntity getUser2(@PathVariable String id) throws Exception {
        return jdbcTemplate.queryForObject("select u_id, u_name from t_user where u_id = ?", new Object[]{id}, new BeanPropertyRowMapper<>(UserEntity.class));
    }

    @GetMapping("count")
    public Long getUserCount() throws Exception {
        return jdbcTemplate.queryForObject("select count(u_id) from t_user", Long.class);
    }

    @GetMapping("batch")
    public List<UserEntity> getBatchUser(@RequestParam(name = "ids") String[] ids) throws Exception {
        String params = Stream.generate(() -> "?").limit(ids.length).collect(Collectors.joining(",", "", ""));
        return jdbcTemplate.query("select * from t_user where u_id in (" + params + ")", ids, new BeanPropertyRowMapper<>(UserEntity.class));
    }




}
